﻿using System.Linq;
using Fee.Orders.DesignWorkflow;
using Fee.ViewModel;
using Microsoft.EntityFrameworkCore;

namespace Fee.Orders.ViewModel
{
    public class DelegateOrderDetailViewModel
    {
        public DelegateOrderDetailViewModel()
        {
        }

        public DelegateOrderDetailViewModel(DelegateOrderDetail detail)
        {
            Id = detail.Id;
            ContractType = detail.ContractType;
            ConstructionType = detail.ConstructionType;
            Contract = new FrameworkContractDetialEditorViewModel(detail.Contract);
            SourceConstructionDetailId = detail.SourceConstructionDetailId;
            Operator = detail.Operator;
            if (detail.Project != null)
                Project = new ProjectSimpleViewModel(detail.Project);

        }

        public ConstructionOperator Operator { get; set; }
        public ConstructionOperator ConstructionOperator { get; set; }
        public int? SourceConstructionDetailId { get; set; }
        public int Id { get; set; }
        public ConstructionType ConstructionType { get; set; }
        public ContractType ContractType { get; set; }

        public FrameworkContractDetialEditorViewModel Contract { get; set; }
        public ProjectSimpleViewModel Project { get; set; }



        /// <summary>
        /// </summary>
        /// <param name="dbContext"></param>
        /// <returns></returns>
        public DelegateOrderDetail ToDelegateOrderDetail(FeeDbContext dbContext)
        {
            var result = Id != 0 ? dbContext.DelegateOrderDetails.First(f => f.Id == Id) : new DelegateOrderDetail();

            result.SourceConstructionDetailId = SourceConstructionDetailId;
            result.ContractType = ContractType;
            result.ConstructionType = ConstructionType;
            result.Contract = dbContext.FrameworkContracts.Include(f => f.Vendor)

                .FirstOrDefault(f => f.Id == Contract.Id);
            // 如果 原来的 建设任务细节id为空，那么一定为创建
            //否则就要指定是操作
            result.Operator = Operator;
            result.Project = dbContext.Projects.FirstOrDefault(f => f.Id == Project.Id);


            return result;
        }
    }
}